package com.practice.bootdemo.controller;

import com.practice.bootdemo.common.R;
import com.practice.bootdemo.common.SpringBeanUtil;
import com.practice.bootdemo.common.SpringBeanUtil2;
import com.practice.bootdemo.service.BeanDemoService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.RequestContextUtils;


/**
 * @author :zhoushunquan
 * @description: bean获取测试
 * @create date: 2022-03-24 17:25:33
 */


@RestController
@RequestMapping(value = "bean")
public class BeanDemoController {

    @Operation(summary = "获取bean测试")
    @PostMapping(value = "getBean1")
    public R<Integer> getBean1() {
        BeanDemoService beanDemoService1= (BeanDemoService) SpringBeanUtil.getBean("beanDemoServiceImpl");
        BeanDemoService beanDemoService2= (BeanDemoService) SpringBeanUtil2.getBean("beanDemoServiceImpl");
        beanDemoService1.printTest();
        beanDemoService2.printTest();

        beanDemoService1= SpringBeanUtil.getBean(BeanDemoService.class);
        beanDemoService2=SpringBeanUtil2.getBean(BeanDemoService.class);

        beanDemoService1.printTest();
        beanDemoService2.printTest();
        return R.ok(1);
    }

    @PostMapping(value = "getBean2")
    public R<Integer> getBean2(HttpServletRequest request, HttpServletRequest response) {
        WebApplicationContext wc = RequestContextUtils.findWebApplicationContext(request);
        BeanDemoService beanDemoService1= (BeanDemoService) wc.getBean("beanDemo1ServiceImpl");
        beanDemoService1.printTest();

        beanDemoService1= SpringBeanUtil.getBean(BeanDemoService.class);
        beanDemoService1.printTest();

//        在service中或者其他后端服务中获取
       /*
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        WebApplicationContext wc = RequestContextUtils.findWebApplicationContext(request);
        WebApplicationContext wc2 = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        wc.getBean("beanName");
        wc2.getBean("beanName");
        */

        return R.ok(1);
    }
}